<template>
  <div 
  :class="{'innerPageTable-box-OneTwo': !useTableSearchBar}"
  class="err innerPageTable-out-flex">
    <!-- 搜索区域 -->
    <SelfAdaption v-if="!useTableSearchBar">
      <Form
        :model="condition"
        ref="conditionForm"
        slot="adaption-bar"
        label-position="top"
        class="ivu-form-no-margin-bottom"
        inline
      >
        <template>
          <!-- 应用名称 -->
          <Form-item :label="$t('module.errCenter.applyName')">
            <Select
              v-model="condition.appId"
              style="width: 100%;"
              
              @on-change="onAppChange"
              :placeholder="$t('module.extend.tip.applyName')"
              clearable
            >
              <Option v-for="app in appList" :value="app.id" :key="app.id">{{ app.appName }}</Option>
            </Select>
          </Form-item>

          <!-- 错误代码 -->
          <Form-item :label="$t('module.errCenter.errorCode')">
            <Input
              type="text"
              :maxlength="30"
              v-model="condition.errorCode"
              :placeholder="$t('module.extend.tip.errorCode')"
              
              style="width: 100%;"
              @on-enter="searchHandler"
            ></Input>
          </Form-item>

          <!-- 错误信息 -->
          <Form-item :label="$t('module.errCenter.errorMessage')">
            <Input
              type="text"
              :maxlength="30"
              v-model="condition.message"
              :placeholder="$t('module.extend.enterErrorMessage')"
              
              style="width: 100%;"
              @on-enter="searchHandler"
            ></Input>
          </Form-item>

          <!-- 查询\重置按钮 -->
          <Form-item prop="button" class="search-solt-btn">
            <RPButton optType="search" @click="searchHandler" />
            <RPButton optType="reset" @click="resetHandler" />
          </Form-item>
        </template>
      </Form>
    </SelfAdaption>
    <InnerPageTable ref="tableRef" :config="config">
      <!-- handler bar 查询/重置-->
      <!--
      <div slot="handle-bar" class="handle-bar-two">
        <RPButton optType="search" @click="searchHandler" />
        <RPButton optType="reset" @click="resetHandler" />
      </div>
      -->
      <!-- table bar 添加-->
      <div slot="table-bar">
        <RPButton optType="create" @click="addHandler()" />
        <!-- <Button @click.native="deleteHandler" icon="md-trash" >{{$t('common.delete')}}</Button> -->
      </div>
      <Form
        :model="condition"
        ref="conditionForm"
        slot="table-search-bar"
        v-if="useTableSearchBar"
        label-position="top"
        class="ivu-form-no-margin-bottom"
        inline
      >
        <template>
          <!-- 应用名称 -->
          <Form-item>
            <Select
              v-model="condition.appId"
              style="width: 100%;"
              
              @on-change="onAppChange"
              :placeholder="$t('module.extend.tip.applyName')"
              clearable
            >
              <Option v-for="app in appList" :value="app.id" :key="app.id">{{ app.appName }}</Option>
            </Select>
          </Form-item>

          <!-- 错误代码 -->
          <Form-item>
            <Input
              type="text"
              :maxlength="30"
              v-model="condition.errorCode"
              :placeholder="$t('module.extend.tip.errorCode')"
              
              style="width: 100%;"
              clearable
              @on-enter="searchHandler"
              @on-blur="searchHandler"
              @on-clear="searchHandler"
            ></Input>
          </Form-item>

          <!-- 错误信息 -->
          <Form-item>
            <Input
              type="text"
              :maxlength="30"
              v-model="condition.message"
              :placeholder="$t('module.extend.enterErrorMessage')"
              
              style="width: 100%;"
              clearable
              @on-enter="searchHandler"
              @on-blur="searchHandler"
              @on-clear="searchHandler"
            ></Input>
          </Form-item>
        </template>
      </Form>
    </InnerPageTable>
  </div>
</template>

<script>
import locales from "./locales.js";
import { errorListCol } from "./columns";
import { getOwnedApplicationByTenantCode } from "@/api/applicationApi";
import { getMessageList, delError, getErrorById } from "@/api/errorCenterApi";
// import { CoreModuleName } from "@/const";
import { CoreModuleName } from "@/const";
import Edit from "./Edit";

const language = $store.state[CoreModuleName].lang || "zh-CN";

const initCondition = function () {
  return {
    appId: "",
    errorCode: "",
    tenantCode: "",
    // errorCodeMessageVOList: [
    //   {
    //     errorMessage: ""
    //   }
    // ]
    message: ""
  };
};

export default {
  name: "error-center",
  mixins: [locales],
  data: () => ({
    condition: initCondition(),
    appList: [],
    userInfo: $store.state[CoreModuleName].userInfo
  }),
  computed: {
    config() {
      const { condition } = this;
      const { userInfo } = $store.state[CoreModuleName];
      if (userInfo.tenantCode) {
        condition.tenantCode = userInfo.tenantCode;
      }

      return {
        loadDataFn: async ({ responseProcess, param }) => {
          let res = await getMessageList(param);
          let records = res.data.records || [];
          for (let item of records) {
            // item.appName = this.findAppName(item.appId);
            // item.appName = item.appName;
            // item.message = this.findMessage(item.errorCodeMessageVOList);
            item.message = item.message;
            item.type = this.findType(item.errorType);
          }

          responseProcess(res.data);
        },
        columnsFn: errorListCol.bind(this),
        initParam: condition,
        autoFirst: true
      };
    },
    errorTypes() {
      return [
        { code: "0", name: this.$t("module.errCenter.error") },
        { code: "1", name: this.$t("module.errCenter.success") },
        { code: "2", name: this.$t("module.errCenter.warn") },
        { code: "3", name: this.$t("module.errCenter.tip") }
      ];
    }
  },

  mounted() {
    this.getApplList();
  },
  methods: {
    findAppName(appId) {
      for (let appInfo of this.appList) {
        if (appInfo.id === appId) {
          return appInfo.appName;
        }
      }
    },
    // findMessage(messages) {
    //   messages = messages || [];
    //   for (let msg of messages) {
    //     if (msg.langCode === language) {
    //       return msg.errorMessage;
    //     }
    //   }
    // },
    findType(typeCode) {
      for (var typeInfo of this.errorTypes) {
        if (typeInfo.code == typeCode) {
          return typeInfo.name;
        }
      }
    },
    // 请求应用列表
    getApplList() {
      let param = {
        tenantCode: this.userInfo.tenantCode,
        isOwned: true
      };
      getOwnedApplicationByTenantCode(param).then(res => {
        this.appList = res.data;
      });
    },
    // 查询
    searchHandler(page = 1) {
      this.$refs.tableRef.load(this.condition, page);
    },
    // 重置
    resetHandler() {
      this.$refs.conditionForm.resetFields(1);
      this.condition = initCondition();
      this.searchHandler();
    },
    async addHandler(row) {
      let messageInfo = {};
      if (row && row.id) {
        messageInfo = await getErrorById(row.id);
        messageInfo = messageInfo.data;
      }

      new this.$pageModal(
        Edit,
        {
          props: {
            appList: this.appList,
            messageInfo: messageInfo,
            errorTypes: this.errorTypes
          }
        },
        reload => reload && this.searchHandler(this.$refs.tableRef.param.pageNum)
      );
    },
    deleteHandler(id) {
      this.$confirm.warning(this.$t("common.confirmDeletion")).then(() =>
        delError([id]).then(() => {
          this.searchHandler();
          this.$message.success({
            content: this.$t("common.deleteSuccess"),
            duration: 3
          });
        })
      );
    },
    onAppChange() {
      this.searchHandler();
    }
  }
};
</script>

<style></style>
